package cn.touna.jss.modules.third.zzc;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.ZhongzhichengProperties;
import cn.touna.jss.common.util.Common;
import cn.touna.jss.common.util.HttpUtil;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.zzc.entity.ZhongzhichengRequestEntity;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 中智诚调用
 *
 * @author Administrator
 */
@Service
public class ZhongzhichengService {
    private static final Logger LOGGER = LogManager.getLogger(ZhongzhichengService.class);

    @Autowired
    private ZhongzhichengProperties zzcProperties;

    /**
     * 中智诚查询黑名单用户信息接口请求
     *
     * @param
     * @return
     * @throws Exception
     */
    @ApiMapping(value = "zhongzhicheng.getBlackList",desc = "中智诚.黑名单")
    public Response getBlackList(ZhongzhichengRequestEntity requestEntity) {
        Response response = ValidUtil.valid(requestEntity);
        if (response != null)
            return response;

        String key = "classpath:log4j2.xml";
        System.out.println(System.getProperty(key));
        JSONObject jsonParams = new JSONObject();
        try {
            jsonParams.put("name", requestEntity.getName());
            jsonParams.put("pid", requestEntity.getIdCard());
            jsonParams.put("mobile", requestEntity.getMobile());
            jsonParams.put("home_address", requestEntity.getHomeAddress());
            jsonParams.put("home_phone", requestEntity.getHomePhone());
            jsonParams.put("work_name", requestEntity.getWorkName());
            jsonParams.put("work_address", requestEntity.getWorkAddress());
            jsonParams.put("address", requestEntity.getAddress());
            jsonParams.put("work_phone", requestEntity.getWorkPhone());
            jsonParams.put("sub_tenant", requestEntity.getSubTenant());
//            String result = getData("POST", jsonParams.toString(), "【中智诚查询黑名单】");

            //设置用户名和密码
            String authSrc = zzcProperties.getAccountName()+":"+zzcProperties.getAccountPwd();
            //对其进行加密
            String auth ="Basic " + Base64.getEncoder().encodeToString(authSrc.getBytes());
            Map<String,String>headers = new HashMap<>();
            headers.put("Authorization",auth);
            String result = HttpUtil.post(zzcProperties.getQueryBlackUserUrl(),jsonParams.toJSONString(),HttpUtil.CONTENT_TYPE_JSON,headers,null,null);
            JSONObject resObj = JSONObject.parseObject(result);
            String error = resObj.getString("error");
            if(!StringUtils.isEmpty(error)){
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL, error);
            }
            return ResponseFactory.success(result);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(),e);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR,e.getMessage());
        }
    }

    private String getData(String type, String jsonParams, String message) throws Exception {

        LOGGER.info(message + "请求为 : {}", zzcProperties.getQueryBlackUserUrl());
        HttpClient c = new HttpClient();
        c.getParams().setContentCharset("UTF-8");
        c.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(zzcProperties.getAccountName(), zzcProperties.getAccountPwd());
        c.getState().setCredentials(AuthScope.ANY, defaultcreds);
        String result = "";
        if ("POST".equals(type)) {
            PostMethod postMethod = new PostMethod(zzcProperties.getQueryBlackUserUrl());
            RequestEntity r = new StringRequestEntity(jsonParams, "application/json", "UTF-8");
            postMethod.setRequestEntity(r);
            c.executeMethod(postMethod);
            result = Common.streamToString(postMethod.getResponseBodyAsStream());
        } else if ("GET".equals(type)) {
            GetMethod getMethod = new GetMethod(zzcProperties.getQueryBlackUserUrl());
            c.executeMethod(getMethod);
            result = Common.streamToString(getMethod.getResponseBodyAsStream());
        }
        return result;
    }
}
